import Vue from 'vue'
import VueRouter from 'vue-router'
import {routerMode} from '../config/env'
import routes from './routes'
import {Storage} from '../config/mUtils'

Vue.use(VueRouter)
const router = new VueRouter({
  routes,
  mode: routerMode,
  strict: process.env.NODE_ENV !== 'production',
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      if (from.meta.keepAlive) {
        from.meta.savedPosition = document.body.scrollTop
      }
      return {x: 0, y: to.meta.savedPosition || 0}
    }
  }
})

router.beforeResolve((to, from, next) => {
  if (to.matched.some(m => m.meta.auth)) {
    let authorized = parseInt(Storage.getStore('u_authorized'))
    if (authorized !== 1) {
      next({path: '/login', query: {referrer: to.fullPath}})
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
